<?php
/**
 * Created by PhpStorm.
 * User: trnall
 * Date: 2020/10/19
 * Time: 14:51
 */

namespace app\sapi\controller\v1;

use app\common\controller\Api;
use app\api\service\OrderService;
use app\api\service\UserService;
use app\common\model\OrderProof;
use app\common\model\OrderLog;
use app\common\model\OrderPay;
use app\common\model\OrderAftersale;
use app\common\model\User;
use app\admin\model\Play;
use app\common\model\Order as OrderModel;
use think\Db;
use think\Exception;
use addons\third\model\Third;
use wechat\wxpay\JsApiPay;

/**
 * 线上订单
 * Class Order
 * @package app\sapi\controller\v1
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function list()
    {
        $pageSize = 20;
        $page = input('page/d', 1);
        $shop_no = input('shop_no/d', '');
        $order_status = input('order_status/d', 0);//0 全部 1 待上传 2 审核中  3 已完成
        $play_no = input('play_no/d', '');
        $user_id = $this->auth->id;
        $play = Play::where(['play_no'=>$play_no])->find();
        if (!$play) {
            $this->error('无此活动信息');
        }
        if ($shop_no) $where['shop_no'] = $shop_no;
        if ($play_no) $where['play_no'] = $play_no;
        switch ($order_status) {
            case 0:
                $where['order_status'] = ['in',[3,6,-9]];
                break;
            case 1:
                $where['order_status'] = 1;
                break;
            case 2:
                $where['order_status'] = 2;
                break;
            case 3:
                $where['order_status'] = ['in',[3,6,-9]];
                break;
            default:
                break;
        }
        $OrderModel = new OrderModel();
        $data = $OrderModel->with(['shop', 'play'])
            ->where($where)
            ->order('id DESC')
            ->page($page, $pageSize)
            ->select();
        foreach ($data as $key => &$value) {
            $value['proof'] = OrderProof::where('play_order_no',$value['play_order_no'])->order('id DESC')->find();
        }
        $this->success('', $data);
    }

    /**
     * 订单详情
     * @param $id
     */
    public function detail(OrderService $orderService)
    {
        $id = input('id/d', 0);
        $detail = $orderService->getOrderDetail($id);
        $this->success('订单详情', $detail);
    }

    public function verifyNum()
    {
        $shop_no = input('shop_no/d', '');
        $where = [
            'order_status' => 2
        ];
        if ($shop_no) $where['shop_no'] = $shop_no;
        $total = (new \app\common\model\Order())->where($where)->count();
        $this->success('', $total);
    }

    public function pass()
    {
        $user_id = $this->auth->id;
        $pay_type = 1;
        $amount = input('amount/d', 0);
        $play_no = input('play_no','', 'strip_tags,htmlspecialchars');
        $play_order_no = input('play_order_no','', 'strip_tags,htmlspecialchars');
        if (!$play_no && !$play_order_no) {
            $this->error('缺少参数');
        }
        if ($play_no) {
            $play_nos = explode(',', $play_no);
            if (!$play_nos) {
                $this->error('参数错误');
            }
            // 判断当前活动有没有
            $PlayModel = new Play();
            $where= [];
            $where['is_pay'] = 0;
            $where['play_no'] = ['in',$play_nos];
            $where['user_id'] = $user_id;
            $play = $PlayModel->where($where)->select();
            if (!$play) $this->error('未查询到相关数据');
            $rebate_amt = 0;
            $all = [];
            foreach ($play as $k => $v) {
                if (!in_array($v['play_status'], [3])) {
                    $this->error('活动状态有误');
                }
                $actual_rebate_amt = OrderModel::where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(actual_rebate_amt+service_charge_amt)');
                $rebate_amt += floatval($actual_rebate_amt);
            }
            // $rebate_amt = 0.1;
            $pay_data = [
                'user_id' => $user_id,
                'pay_no' => $this->generateNo(['biz_tag'=>'pay_no','len'=>12,'int_prefix'=>8]),
                'pay_mod' => $pay_type==1?'wechat':'alipay',
                'amount' => round($rebate_amt,2),
                'pay_time' => time(),
                'play_nos' => $play_no,
            ];
            foreach ($play as $k => $v) {
                $orders = OrderModel::where(['play_no'=>$v['play_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->field('play_no,play_order_no')->select();
                foreach ($orders as $key => $value) {
                    $data = [];
                    $data['pay_no'] = $pay_data['pay_no'];
                    $data['play_no'] = $value['play_no'];
                    $data['play_order_no'] = $value['play_order_no'];
                    $all[] = $data;
                }
            }
        } elseif ($play_order_no) {
            $play_order_nos = explode(',', $play_order_no);
            if (!$play_order_nos) {
                $this->error('参数错误');
            }
            // 判断当前活动有没有
            $OrderModel = new OrderModel();
            $where= [];
            $where['play_order_no'] = ['in',$play_order_nos];
            // $where['user_id'] = $user_id;
            $order = $OrderModel->where($where)->select();
            if (!$order) $this->error('未查询到相关数据');
            $rebate_amt = 0;
            $all = [];
            foreach ($order as $k => $v) {
                if (!in_array($v['order_status'], [3,6,-9]) || $v['is_pay']!=0) {
                    $this->error('活动状态有误');
                }
                $rebate_amt += round($v['actual_rebate_amt']+$v['service_charge_amt'],2);
            }
            // $rebate_amt = 0.1;
            $pay_data = [
                'user_id' => $user_id,
                'pay_no' => $this->generateNo(['biz_tag'=>'pay_no','len'=>12,'int_prefix'=>8]),
                'pay_mod' => $pay_type==1?'wechat':'alipay',
                'amount' => $rebate_amt,
                'pay_time' => time(),
                'play_nos' => $play_order_no,
            ];
            foreach ($order as $key => $value) {
                $all[$key]['pay_no'] = $pay_data['pay_no'];
                $all[$key]['play_no'] = $value['play_no'];
                $all[$key]['play_order_no'] = $value['play_order_no'];
            }
        }
        Db::startTrans();
        try {
            // $pay = OrderPay::where(['user_id'=>$user_id,'play_nos'=>$play_order_no])->find();
            // if (isset($pay['create_dt']) && time()-strtotime($pay['create_dt'])<10) {
            //     $this->error('您近期支付过该订单，请确认是否继续支付？');
            // }
            if (isset($pay_data) && $pay_data) {
                OrderPay::create($pay_data);
            }
            if (isset($all) && $all) {
                Db::name('order_pay_item')->insertAll($all);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::write('支付账单：'.$e->getMessage());
            $this->error('支付有误');
        }
        if (isset($all) && $all) {
            $config = get_addon_config('epay');
            if ($pay_data['pay_mod']=='alipay') {
                $params = [
                    'amount'=>$rebate_amt,
                    'orderid'=>$pay_data['pay_no'],
                    'type'=>$pay_data['pay_mod'],
                    'title'=>"商家支付账单",
                    'method'=>"wap",
                    'notifyurl'=>request()->root(true) . $config['alipay']['notify_url'],
                    'returnurl'=>request()->root(true) . $config['alipay']['return_url'],
                ];
                $res = \addons\epay\library\Service::submitOrder($params);
                $this->success('',[$res],2);
            } elseif ($pay_data['pay_mod']=='wechat') {
                $unionid = User::where('id',$user_id)->value('unionid');
                $openid = Db::name('third')->where(['unionid'=>$unionid,'platform'=>'miniprogram'])->value('openid');
                $params = [
                    'amount'=>$rebate_amt,
                    'orderid'=>$pay_data['pay_no'],
                    'type'=>'wechat',
                    'title'=>"商家支付账单",
                    'method'=>"miniapp",
                    'notifyurl'=>request()->root(true) . $config['wechat']['notify_url'],
                    'openid'=>$openid,
                ];
                $res = \addons\epay\library\Service::submitOrder($params);
                $this->success('',$res,2);
            }
        }
        $this->success('活动已结束');
    }

    public function reject()
    {
        $play_order_no = input('play_order_no/d','');
        $desc = input('desc', '');
        $img = input('img', '');
        $remark = input('remark', '');
        if (!$play_order_no || !$desc) {
            $this->error('缺少参数');
        }
        $OrderProof = new OrderProof();
        $proof = $OrderProof->where(['play_order_no'=>$play_order_no,'merchant_id' => $this->auth->id])->order('id DESC')->find();
        if (!$proof || $proof->handle_status != 1) $this->error('未查询到相关数据');
        $extend = [
            'handle_merchant_id' => $this->auth->id,
            'handle_merchant_desc' => json_encode(['desc'=>$desc,'img'=>$img,'remark'=>$remark],JSON_UNESCAPED_UNICODE),
        ];
        $res = $OrderProof->reject($proof['id'], $extend, $this->auth->nickname, $this->auth->id);
        if (!$res) $this->error('处理失败', $res);
        $this->success('处理成功');
    }


    /**
     * 异常订单
     * @DateTime 2023-04-09T19:40:17+0800
     * @return   [type]                   [description]
     */
    public function abnormalOrder()
    {
        $pageSize = 20;
        $page = input('page/d', 1);
        $status = input('status/d', 1);  // 处理中传1，已完成传2
        $list = [];
        $where = ['order_aftersale_id'=>['>',0],'merchant_id'=>$this->auth->id];
        $where['handle_status'] = ['in',[0,-1]];  // 待审核，已驳回
        if ($status==2) {
            $where['handle_status'] = ['in',[1,3]]; // 已完成，已取消
        }
        $OrderProof = OrderProof::where($where)->page($page,$pageSize)->select();
        foreach ($OrderProof as $key => $value) {
            $order = OrderModel::where(['play_order_no'=>$value['play_order_no']])->with(['shop', 'play'])->find();
            $list[$key] = $order;
            $list[$key]['proof'] = $value->toArray();

            // 异常信息
            $handle_merchant_desc = json_decode($list[$key]['proof']['handle_merchant_desc'],1);
            $list[$key]['desc'] = '';
            if (isset($handle_merchant_desc['desc'])) {
                $list[$key]['desc'] = $handle_merchant_desc['desc'];
            }
            $list[$key]['img'] = [];
            if (isset($handle_merchant_desc['img'])) {
                $img = explode(',', $handle_merchant_desc['img']);
                foreach ($img as $k => $v) {
                    $img[$k] = config('upload_domain').$v;
                }
                $list[$key]['img'] = $img;
            }
            $list[$key]['remark'] = '';
            if (isset($handle_merchant_desc['remark'])) {
                $list[$key]['remark'] = $handle_merchant_desc['remark'];
            }
            // 客服审核结果在售后订单表中
            // $aftersale = OrderAftersale::where(['type'=>['in',['驳回用户订单申请','确认通过审核']],'play_order_no'=>$value['play_order_no']])->find();
            // if ($aftersale && $aftersale['content']) {
            //     $content = json_decode($aftersale['content'],1);
            //     if (isset($content['aftersale'])) {
            //         $list[$key]['aftersale'] = $content['aftersale'];
            //     }
            //     if (isset($content['remark'])) {
            //         $list[$key]['file'] = config('upload_domain').$content['file'];
            //     }
            //     if (isset($content['remark'])) {
            //         $list[$key]['remark2'] = $content['remark'];
            //     }
            // }
            $list[$key]['aftersale'] = '';
            $list[$key]['file'] = '';
            $list[$key]['remark2'] = '';
            if ($order['order_status']==-9) {// 驳回商家异常
                $aftersale = OrderAftersale::where(['type'=>['in',['客服审核拟扣吃豆通过','客服审核拟取消或扣吃豆通过']],'play_order_no'=>$value['play_order_no']])->find();
                if ($aftersale && $aftersale['content']) {
                    $content = json_decode($aftersale['content'],1);
                    if (isset($content['sj']['desc'])) {
                        $list[$key]['aftersale'] = $content['sj']['desc'];
                    }
                    if (isset($content['yh']['file'])) {
                        $list[$key]['file'] = config('upload_domain').$content['yh']['file'];
                    }
                    if (isset($content['sj']['remark'])) {
                        $list[$key]['remark2'] = $content['sj']['remark'];
                    }
                }
            }
            if ($order['order_status']==-4) {// 取消订单
                $aftersale = OrderAftersale::where(['type'=>['in',['客服审核拟扣吃豆通过','客服审核拟取消或扣吃豆通过']],'play_order_no'=>$value['play_order_no']])->find();
                if ($aftersale && $aftersale['content']) {
                    $content = json_decode($aftersale['content'],1);
                    if (isset($content['sj']['desc'])) {
                        $list[$key]['aftersale'] = $content['sj']['desc'];
                    }
                    if (isset($content['yh']['file'])) {
                        $list[$key]['file'] = config('upload_domain').$content['yh']['file'];
                    }
                    if (isset($content['sj']['remark'])) {
                        $list[$key]['remark2'] = $content['sj']['remark'];
                    }
                }
            }
        }
        $this->success('',$list);
    }
}